//
//  DHTabBarController.m
//  hehenianMobile
//
//  Created by huihu on 15/4/26.
//  Copyright (c) 2015年 huihu. All rights reserved.
//

#import "DHTabBarViewController.h"
#import "DHTabBar.h"
#import "AppDelegate.h"
#import "DHNavigationViewController.h"
#import "DHTabBarButton.h"

#import "LawLibraryViewController.h"
#import "InteractionViewController.h"
#import "OnlineServiceViewController.h"
#import "ConvenienceGuideViewController.h"
#import "QuestionnaireViewController.h"
#import "GovernmentInformationViewController.h"

//#import "LoginViewController.h"

#import "UIImage+MJ.h"
#import "IAuthQuery.h"
#import "CoreManager.h"
#import "HHNUtility.h"
#import "BaoController.h"
#import "IAuthClient.h"
#import "Colours.h"

@interface DHTabBarViewController() <DHTabBarDelegate>
@property (nonatomic,strong)  LawLibraryViewController *HomePageVC;
@property (nonatomic,strong) InteractionViewController *interactionVC;//
@property (nonatomic, strong) OnlineServiceViewController *onlineVC;
@property (nonatomic,strong)  ConvenienceGuideViewController *convenienceVC;
@property (nonatomic,strong) QuestionnaireViewController *questionVC;
@property (nonatomic,strong) GovernmentInformationViewController *governmentVc;
@end

@implementation DHTabBarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(backHome:) name:@"backHome" object:nil];
    
    // 初始化tabbar
    [self setupTabbar];
    // 初始化所有的子控制器
    [self setupAllChildViewControllers];
    
    NSTimer *timer = [NSTimer timerWithTimeInterval:60*3 target:self selector:@selector(heartBeat) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

-(void) heartBeat {
    
    /**
     *  app 心跳
     */
    [GetCoreI(IAuthClient) appheartBeatSuccessBlock:^(BOOL islogin) {
        
        if (!islogin) {
            
            [self autoLogin];
        }
    } andFailBlock:^(NSString *msg) {
        
        
    }];
}





-(void) autoLogin {
    
    NSString * userId = [GetCoreI(IAuthQuery) getUserId];
    if (userId != nil && userId.length > 1) {
        NSString *userName = [GetCoreI(IAuthQuery) getUserName];
        NSString *password = [GetCoreI(IAuthQuery) getPassword:userName];
        [GetCoreI(IAuthClient) requestLoginWithUserName:userName password:password code:@"" SuccBlock:^(void) {
            
            
        }failBLock:^(NSString *msg) {
            
            
        }];
    }
    
}



-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}


/**
 *  使用popToViewController导致的UITabBarButton重叠的问题
 *
 */
-(void)viewWillLayoutSubviews{
    
    [super viewWillLayoutSubviews];
    
    for (UIView *child in self.tabBar.subviews) {
        
        if ([child isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            
            [child removeFromSuperview];
        }
    }
}

///**
// *  解决bug tabbar 底部一根黑线
// */
//-(void)HiddenTabarLine
//{
//    for (id view in self.tabBar.subviews) {
//        if ([view isKindOfClass:[UIImageView class]]) {
//            UIImageView *image=(UIImageView *)view;
//            image.frame=CGRectMake(0, 49-TabbarHeight, self.view.frame.size.width, TabbarHeight);
//            image.backgroundColor=[UIColor clearColor];
//        }
//    }
//}


-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"backHome" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/**
 *  返回首页
 */
-(void)backHome:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    self.selectedIndex = 0;
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 删除系统自动生成的UITabBarButton
    for (UIView *child in self.tabBar.subviews) {
        if ([child isKindOfClass:[UIControl class]]) {
            [child removeFromSuperview];
        }
    }
}


/**
 *  初始化tabbar
 */
- (void)setupTabbar
{
    
    DHTabBar *customTabBar = [[DHTabBar alloc] init];
    customTabBar.frame =self.tabBar.bounds;
    customTabBar.delegate = self;
    
    CGRect rect=customTabBar.frame;
    rect.size.height=TabbarHeight;
    rect.origin.y-=TabbarHeight-50;
    customTabBar.frame=rect;
    
    [self.tabBar setShadowImage:[UIImage new]];//设置shadowimage 为一张空图片
    self.tabBar.backgroundImage=[UIImage imageNamed:@"home_bottom"];
    [self.tabBar addSubview:customTabBar];
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, -1, rect.size.width, 1)];
    topView.backgroundColor = [UIColor colorWithRed:((float)((0xdcdcdc & 0xFF0000) >> 16))/255.0 green:((float)((0xdcdcdc & 0xFF00) >> 8))/255.0 blue:((float)(0xdcdcdc & 0xFF))/255.0 alpha:0.5];
    [self.tabBar addSubview:topView];
    
    self.customTabBar = customTabBar;
    
}
#pragma mark - tabbar的代理方法
/**
 *  监听tabbar按钮的改变
 *  @param from   原来选中的位置
 *  @param to     最新选中的位置
 */
- (void)tabBar:(DHTabBar *)tabBar didSelectedButtonFrom:(int)from to:(int)to
{
    self.selectedIndex = to;
    
    //        //[self.HomePageVC refresh];
    //    }else
    if(to==1)
    {//点击了我的账户

//        [self.financingVC loadWebView];
        //        if ([GetCoreI(IAuthQuery) getUserId].length<=0) {
        //            //还没有登录
        //            self.selectedIndex=from;
        //            LoginViewController *loginVC=[[LoginViewController alloc]init];
        //
        //            loginVC.delegate=self;
        //            loginVC.view.tag=1;
        //
        //            DHNavigationViewController *navigationVC=[[DHNavigationViewController alloc] initWithRootViewController:loginVC];
        //            [self.view.window.rootViewController presentViewController:navigationVC animated:YES completion:nil];
        //
        //        }
        //
    }
    //    else if(to==2)
    //    {//更多
    //        if ([GetCoreI(IAuthQuery) getUserId].length<=0) {
    //            //还没有登录
    //            self.selectedIndex=from;
    //            LoginViewController *loginVC=[[LoginViewController alloc]init];
    //            loginVC.delegate=self;
    ////            loginVC.view.tag=2;
    //
    //            DHNavigationViewController *navigationVC=[[DHNavigationViewController alloc] initWithRootViewController:loginVC];
    //            [self.view.window.rootViewController presentViewController:navigationVC animated:YES completion:nil];
    //
    //
    //        }
    //    }else
    if (to == 3) {
        //        if ([GetCoreI(IAuthQuery) getUserId].length<=0) {
        //            //还没有登录
        //            self.selectedIndex=from;
        //            LoginViewController *loginVC=[[LoginViewController alloc]init];
        //            loginVC.delegate=self;
        //            loginVC.view.tag=3;
        //
        //            DHNavigationViewController *navigationVC=[[DHNavigationViewController alloc] initWithRootViewController:loginVC];
        //            [self.view.window.rootViewController presentViewController:navigationVC animated:YES completion:nil];
        //
        //
        //        }
        
    }
}
#pragma mark 实现委托LoginViewControllerDelegate
//-(void)loginViewLoginSucceed:(LoginViewController *)loginView
//{
//    NSNumber *login_tag=[NSNumber numberWithInteger:loginView.view.tag];
//    //登录成功,
//    NSDictionary *dict=@{@"index":login_tag};
//    //创建  发送通知
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"itemSelected" object:nil userInfo:dict];
//    //[self.navigationController popToRootViewControllerAnimated:YES];
//}
//
//-(void) loginViewDidDisappear:(LoginViewController *)loginView {
//    
//    [self.tabBarController setSelectedIndex:0];
//    //登录成功,
//    NSDictionary *dict=@{@"index":@"0"};
//    //创建  发送通知
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"itemSelected" object:nil userInfo:dict];
//}

/**
 *  初始化所有的子控制器
 */
- (void)setupAllChildViewControllers
{
    //政务资讯
    GovernmentInformationViewController *governmentVc = [[GovernmentInformationViewController alloc] initWithNibName:@"GovernmentInformationViewController" bundle:nil];
    [self setupChildViewController:governmentVc title:@"政务资讯" imageName:@"tab_icon1" selectedImageName:@"tab_icon1_press" andSelectedBtnTitleColor:[UIColor colorFromHexString:@"#F99E44"]];
 //   #F99E44
    // 法律文库
    LawLibraryViewController *HomePageVC = [[LawLibraryViewController alloc] initWithNibName:@"LawLibraryViewController" bundle:nil];
    [self setupChildViewController:HomePageVC title:@"法律文库" imageName:@"tab_icon2" selectedImageName:@"tab_icon2_press" andSelectedBtnTitleColor:[UIColor colorFromHexString:@"#20C85C"]];
    self.HomePageVC = HomePageVC;

    // 警民互动
    InteractionViewController *interactionVC  = [[InteractionViewController alloc]  initWithNibName:@"InteractionViewController" bundle:nil];
    [self setupChildViewController:interactionVC title:@"警民互动" imageName:@"tab_icon3" selectedImageName:@"tab_icon3_press" andSelectedBtnTitleColor:[UIColor colorFromHexString:@"#2AA3EB"]];
    self.interactionVC = interactionVC;
    
    //在线服务
    OnlineServiceViewController *onlineVC = [[OnlineServiceViewController alloc] initWithNibName:@"OnlineServiceViewController" bundle:nil];
    [self setupChildViewController:onlineVC title:@"在线服务" imageName:@"tab_icon4" selectedImageName:@"tab_icon4_press" andSelectedBtnTitleColor:[UIColor colorFromHexString:@"#9C44EC"]];
    self.onlineVC = onlineVC;
    
    //便民指南
    ConvenienceGuideViewController *convenienceVC  = [[ConvenienceGuideViewController alloc] initWithNibName:@"ConvenienceGuideViewController" bundle:nil];
    [self setupChildViewController:convenienceVC title:@"便民指南" imageName:@"tab_icon5" selectedImageName:@"tab_icon5_press" andSelectedBtnTitleColor:[UIColor colorFromHexString:@"#F954CE"]];
    self.convenienceVC = convenienceVC;
    
    //调查问卷
    QuestionnaireViewController *questionVC  = [[QuestionnaireViewController alloc] initWithNibName:@"QuestionnaireViewController" bundle:nil];
    [self setupChildViewController:questionVC title:@"调查问卷" imageName:@"tab_icon6" selectedImageName:@"tab_icon6_press" andSelectedBtnTitleColor:[UIColor colorFromHexString:@"#F34853"]];
    self.questionVC = questionVC;

    self.governmentVc = governmentVc;
}

/**
 *  初始化一个子控制器
 *
 *  @param childVc           需要初始化的子控制器
 *  @param title             标题
 *  @param imageName         图标
 *  @param selectedImageName 选中的图标
 */
- (void)setupChildViewController:(UIViewController *)childVc title:(NSString *)title imageName:(NSString *)imageName selectedImageName:(NSString *)selectedImageName andSelectedBtnTitleColor:(UIColor *)color
{
    // 1.设置控制器的属性
    childVc.title = title;
    // 设置图标
    childVc.tabBarItem.image = [UIImage imageWithName:imageName];
    // 设置选中的图标
    UIImage *selectedImage = [UIImage imageWithName:selectedImageName];
    if (iOS7_OR_LATER) {
        childVc.tabBarItem.selectedImage = [selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    } else {
        childVc.tabBarItem.selectedImage = selectedImage;
    }
    
    
    // 2.包装一个导航控制器
    DHNavigationViewController *nav = [[DHNavigationViewController alloc] initWithRootViewController:childVc];
    
    [self addChildViewController:nav];
    
    // 3.添加tabbar内部的按钮
    [self.customTabBar addTabBarButtonWithItem:childVc.tabBarItem andSelectBtnColor:color];
}

@end
